<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from "vue";
import { RefreshLeft, Position, Check } from "@element-plus/icons-vue";
import { ElNotification, ElForm } from "element-plus";
import { getDictListAll as getDicts } from "@/api/system";
import {
  getTableDetail,
  getColumns,
  sync,
  update,
  save,
  generator
} from "@/api/generator";
import { useRoute } from "vue-router";

const ruleForm = ref<InstanceType<typeof ElForm>>();
const route = useRoute();
const activeName = ref("first");
const tableName = ref("");
const tableHeight = ref(550);
const columnLoading = ref(false);
const loading = ref(false);
const configLoading = ref(false);
const dicts = ref([]);
const syncLoading = ref(false);
const genLoading = ref(false);
const form = reactive({
  data: {
    id: null,
    tableName: "",
    author: "",
    pack: "",
    path: "",
    moduleName: "",
    cover: "false",
    apiPath: "",
    prefix: "",
    apiAlias: null
  }
});
const rules = reactive({
  data: {
    author: [{ required: true, message: "作者不能为空", trigger: "blur" }],
    pack: [{ required: true, message: "包路径不能为空", trigger: "blur" }],
    moduleName: [
      { required: true, message: "包路径不能为空", trigger: "blur" }
    ],
    path: [{ required: true, message: "前端路径不能为空", trigger: "blur" }],
    apiAlias: [
      { required: true, message: "接口名称不能为空", trigger: "blur" }
    ],
    cover: [{ required: true, message: "不能为空", trigger: "blur" }]
  }
});
const tableData = reactive({
  data: []
});
const init = async () => {
  loading.value = true;
  let cols = await getColumns({ tableName: tableName.value });
  tableData.data = cols.content;
  loading.value = false;
};
onMounted(() => {
  tableHeight.value = document.documentElement.clientHeight - 385;
  tableName.value = route.params.tableName;
  nextTick(() => {
    init();
    getTableDetail(tableName.value).then(data => {
      form.data = data;
      form.data.cover = form.data.cover.toString();
    });
    getDicts().then(data => {
      dicts.value = data;
    });
  });
});
const syncTable = () => {
  syncLoading.value = true;
  sync([tableName.value])
    .then(() => {
      init();
      ElNotification({
        title: "系统提示",
        message: "同步成功",
        type: "success"
      });
      syncLoading.value = false;
    })
    .then(() => {
      syncLoading.value = false;
    });
};
const doSubmit = () => {
  ruleForm.value.validate(valid => {
    if (valid) {
      configLoading.value = true;
      update(form.data)
        .then(res => {
          ElNotification({
            title: "系统提示",
            message: "保存成功",
            type: "success"
          });
          form.data = res;
          form.data.cover = form.data.cover.toString();
          configLoading.value = false;
        })
        .catch(err => {
          configLoading.value = false;
          console.log(err.response.data.message);
        });
    }
  });
};
const toGen = () => {
  genLoading.value = true;
  save(tableData.data)
    .then(res => {
      ElNotification({
        title: "系统提示",
        message: "保存成功",
        type: "success"
      });
      // 生成代码
      generator(tableName.value, 0)
        .then(data => {
          genLoading.value = false;
          ElNotification({
            title: "系统提示",
            message: "生成成功",
            type: "success"
          });
        })
        .catch(err => {
          genLoading.value = false;
          console.log(err.response.data.message);
        });
    })
    .catch(err => {
      genLoading.value = false;
      console.log(err.response.data.message);
    });
};
const saveColumnConfig = () => {
  columnLoading.value = true;
  save(tableData.data)
    .then(() => {
      ElNotification({
        title: "系统提示",
        message: "保存成功",
        type: "success"
      });
      columnLoading.value = false;
    })
    .catch(err => {
      columnLoading.value = false;
      console.log(err.response.data.message);
    });
};
</script>

<template>
  <div class="app-container">
    <el-row :gutter="15">
      <el-col style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <template v-slot:header>
            <div class="clearfix">
              <span class="role-span">字段配置：{{ tableName }}</span>
              <el-button
                :loading="genLoading"
                :icon="Position"
                size="mini"
                style="float: right; padding: 6px 9px"
                type="success"
                @click="toGen"
                >保存&生成</el-button
              >
              <el-button
                :loading="columnLoading"
                :icon="Check"
                size="mini"
                style="float: right; padding: 6px 9px; margin-right: 9px"
                type="primary"
                @click="saveColumnConfig"
                >保存</el-button
              >
              <el-tooltip
                class="item"
                effect="dark"
                content="数据库中表字段变动时使用该功能"
                placement="top-start"
              >
                <el-button
                  :loading="syncLoading"
                  :icon="RefreshLeft"
                  size="mini"
                  style="float: right; padding: 6px 9px"
                  type="info"
                  @click="syncTable"
                  >同步</el-button
                >
              </el-tooltip>
            </div>
          </template>
          <el-form size="small" label-width="90px">
            <el-table
              v-loading="loading"
              :data="tableData.data"
              :max-height="tableHeight"
              size="small"
              style="width: 100%; margin-bottom: 15px"
            >
              <el-table-column
                prop="columnName"
                width="110px"
                label="字段名称"
              />
              <el-table-column
                prop="columnType"
                width="110px"
                label="字段类型"
              />
              <el-table-column prop="remark" label="字段描述">
                <template #default="scope">
                  <el-input
                    v-model="tableData.data[scope.$index].remark"
                    size="mini"
                    class="edit-input"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="必填" width="80px">
                <template #default="scope">
                  <el-checkbox v-model="tableData.data[scope.$index].notNull" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="列表" width="80px">
                <template #default="scope">
                  <el-checkbox
                    v-model="tableData.data[scope.$index].listShow"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="表单" width="80px">
                <template #default="scope">
                  <el-checkbox
                    v-model="tableData.data[scope.$index].formShow"
                  />
                </template>
              </el-table-column>
              <el-table-column label="表单类型">
                <template #default="scope">
                  <el-select
                    v-model="tableData.data[scope.$index].formType"
                    filterable
                    class="edit-input"
                    clearable
                    size="mini"
                    placeholder="请选择"
                  >
                    <el-option label="文本框" value="Input" />
                    <el-option label="文本域" value="Textarea" />
                    <el-option label="单选框" value="Radio" />
                    <el-option label="下拉框" value="Select" />
                    <el-option label="日期框" value="Date" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="查询方式">
                <template #default="scope">
                  <el-select
                    v-model="tableData.data[scope.$index].queryType"
                    filterable
                    class="edit-input"
                    clearable
                    size="mini"
                    placeholder="请选择"
                  >
                    <el-option label="=" value="=" />
                    <el-option label="!=" value="!=" />
                    <el-option label=">=" value=">=" />
                    <el-option label="<=" value="<=" />
                    <el-option label="Like" value="Like" />
                    <el-option label="NotNull" value="NotNull" />
                    <el-option label="BetWeen" value="BetWeen" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联字典">
                <template #default="scope">
                  <el-select
                    v-model="tableData.data[scope.$index].dictName"
                    filterable
                    class="edit-input"
                    clearable
                    size="mini"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dicts"
                      :key="item.id"
                      :label="item.remark === '' ? item.name : item.remark"
                      :value="item.name"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-card>
      </el-col>
      <el-col>
        <el-card class="box-card" shadow="never">
          <template v-slot:header>
            <div class="clearfix">
              <span class="role-span">生成配置</span>
              <el-button
                :loading="configLoading"
                :icon="Check"
                size="mini"
                style="float: right; padding: 6px 9px"
                type="primary"
                @click="doSubmit"
                >保存</el-button
              >
            </div>
          </template>
          <el-form
            ref="ruleForm"
            :model="form.data"
            :rules="rules.data"
            size="small"
            label-width="78px"
          >
            <el-form-item label="作者名称" prop="author">
              <el-input v-model="form.data.author" style="width: 40%" />
              <span style="margin-left: 10px; color: #c0c0c0"
                >类上面的作者名称</span
              >
            </el-form-item>
            <el-form-item label="模块名称" prop="moduleName">
              <el-input v-model="form.data.moduleName" style="width: 40%" />
              <span style="margin-left: 10px; color: #c0c0c0"
                >模块的名称，请选择项目中已存在的模块</span
              >
            </el-form-item>
            <el-form-item label="至于包下" prop="pack">
              <el-input v-model="form.data.pack" style="width: 40%" />
              <span style="margin-left: 10px; color: #c0c0c0"
                >项目包的名称，生成的代码放到哪个包里面</span
              >
            </el-form-item>
            <el-form-item label="接口名称" prop="apiAlias">
              <el-input v-model="form.data.apiAlias" style="width: 40%" />
              <span style="margin-left: 10px; color: #c0c0c0"
                >接口的名称，用于控制器与接口文档中</span
              >
            </el-form-item>
            <el-form-item label="前端路径" prop="path">
              <el-input v-model="form.data.path" style="width: 40%" />
              <span style="margin-left: 10px; color: #c0c0c0"
                >输入views文件夹下的目录，不存在即创建</span
              >
            </el-form-item>
            <!--            <el-form-item label="接口目录">-->
            <!--              <el-input v-model="form.apiPath" style="width: 40%" />-->
            <!--              <span style="color: #C0C0C0;margin-left: 10px;">Api存放路径[src/api]，为空则自动生成路径</span>-->
            <!--            </el-form-item>-->
            <el-form-item label="去表前缀" prop="prefix">
              <el-input
                v-model="form.data.prefix"
                placeholder="默认不去除表前缀"
                style="width: 40%"
              />
              <span style="margin-left: 10px; color: #c0c0c0"
                >默认不去除表前缀，可自定义</span
              >
            </el-form-item>
            <el-form-item label="是否覆盖" prop="cover">
              <el-radio-group
                v-model="form.data.cover"
                size="mini"
                style="width: 40%"
              >
                <el-radio-button label="true">是</el-radio-button>
                <el-radio-button label="false">否</el-radio-button>
              </el-radio-group>
              <span style="margin-left: 10px; color: #c0c0c0"
                >谨防误操作，请慎重选择</span
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
